﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.Data;
using Microsoft.Win32;

namespace TongJi
{


    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public static string GET_TONGJI_LIST_URL = "http://41416.com/api/json_PlayerInfo?mid={0}&tag={1}&sid={2}&gameusername={3}&sign={4}";
        public static string GET_ACCOUNT_LIST_URL = "http://41416.com/api/json_MemberList?mid={0}&gid={1}&sid={2}&sign={3}";
        //mid=推广渠道id
        //tag=游戏简称
        //sid=服 zoneid
        //gid游戏id
        //

        public string TPL_NAME { get;set; }
        public string GAME_NAME { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            TPL_NAME = "";
            GAME_NAME = "";
        }

        public string getPage(String url)
        {
            WebResponse result = null;

            try
            {
                WebRequest req = WebRequest.Create(url);
                result = req.GetResponse();
                Stream ReceiveStream = result.GetResponseStream();

                //read the stream into a string
                StreamReader sr = new StreamReader(ReceiveStream);
                string resultstring = sr.ReadToEnd();

                return resultstring;
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
                return null;
            }
            finally
            {
                if (result != null)
                {
                    result.Close();
                }
                
            }

        }

        private void GridViewColumnHeader_Click(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource is GridViewColumnHeader)
            {
                //Get clicked column
                GridViewColumn clickedColumn = (e.OriginalSource as GridViewColumnHeader).Column;   //得到单击的列
                if (clickedColumn != null)
                {
                    //Get binding property of clicked column
                    string bindingProperty = (clickedColumn.DisplayMemberBinding as Binding).Path.Path; //得到单击列所绑定的属性
                    SortDescriptionCollection sdc = lv.Items.SortDescriptions;
                    ListSortDirection sortDirection = ListSortDirection.Ascending;
                    if (sdc.Count > 0)
                    {
                        SortDescription sd = sdc[0];
                        sortDirection = (ListSortDirection)((((int)sd.Direction) + 1) % 2);  //判断此列当前的排序方式:升序0,倒序1,并取反进行排序。
                        sdc.Clear();
                    }
                    sdc.Add(new SortDescription(bindingProperty, sortDirection));
                }
            }
        }

        public DataTable m_datetable;
        public DataTable sw_database;
        private delegate void UpdateProgressBarDelegate(System.Windows.DependencyProperty dp, Object value);
        private void newDataTable()
        {
            m_datetable = new DataTable();
            m_datetable.Columns.Add("账号", typeof(string));
            m_datetable.Columns.Add("角色名", typeof(string));
            m_datetable.Columns.Add("等级", typeof(int));
            m_datetable.Columns.Add("性别", typeof(string));
            m_datetable.Columns.Add("职业", typeof(string));
            m_datetable.Columns.Add("元宝", typeof(int));
            m_datetable.Columns.Add("绑定元宝", typeof(int));
            m_datetable.Columns.Add("铜钱", typeof(int));
            m_datetable.Columns.Add("绑定铜钱", typeof(int));
            m_datetable.Columns.Add("是否在线", typeof(int));
            m_datetable.Columns.Add("注册时间", typeof(DateTime));
        }
        public string getFile(string fileName) 
        {
            return System.IO.File.ReadAllText(fileName);
        }
        private void addRows(DataTable data,JObject jobject,string account)
        {
            var 角色名 = jobject["result"][account]["name"].ToString();
            var 等级 = jobject["result"][account]["level"].ToString();
            var 性别 = jobject["result"][account]["gender"].ToString();
            var 职业 = jobject["result"][account]["job"].ToString();
            var 元宝 = jobject["result"][account]["gold"].ToString();
            var 绑定元宝 = jobject["result"][account]["bind_gold"].ToString();
            var 铜钱 = jobject["result"][account]["copper"].ToString();
            var 绑定铜钱 = jobject["result"][account]["bind_copper"].ToString();
            var 是否在线 = jobject["result"][account]["online"].ToString();

            var begtime = Convert.ToInt64(jobject["result"][account]["regtime"]);
            var 注册时间 = new DateTime(1970, 1, 1, 0, 8, 0);
            注册时间 = 注册时间.AddSeconds(begtime);

            m_datetable.Rows.Add(account,
            角色名,
            等级,
            性别,
            职业,
            元宝,
            绑定元宝,
            铜钱,
            绑定铜钱,
            是否在线,
            注册时间.ToString("yyyy-MM-dd HH:mm:ss"));
        }
        private bool checkJSON(string str) 
        {
            if (str.IndexOf("{") > -1 && str.IndexOf("}") > -1 && str.IndexOf(":") > -1)
                return true;
            else
                return false;
        }
        private void loadDate()
        {/*
            var strs = getFile("userlist.txt").Replace("\r", "").Split('\n');
            newDataTable();
            progressbar1.Maximum = strs.Length;
            progressbar1.Value = 0;
            double value = 0;

            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(progressbar1.SetValue);
            foreach (string str in strs)
            {
                value += 1;

                if (!(str.Length == 15)) goto geton;
                string getPageStr = getPage(string.Format(textbox1.Text, UserMd5(str + "dfjn1xk51"), str));
                if (!checkJSON(getPageStr)) goto geton;
                JObject jo = (JObject)JsonConvert.DeserializeObject(getPageStr);
  
                string result = jo["result"].ToString();

                if (result.Length > 15) addRows(m_datetable, jo, str);

            geton:
                Dispatcher.Invoke(updatePbDelegate,System.Windows.Threading.DispatcherPriority.Background,new object[] { ProgressBar.ValueProperty, value });
            continue;

            }
            sw_database = m_datetable.Clone();
            sw_database = m_datetable;
            lv.DataContext = sw_database;*/
        }

        /**/
        /// <summary>
        /// MD5　32位加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UserMd5(string str)
        {
            string cl = str;
            string pwd = "";
            MD5 md5 = MD5.Create();//实例化一个md5对像
            // 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
            // 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得
            for (int i = 0; i < s.Length; i++)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符
                if (s[i].ToString("x").Length == 1)
                {
                    pwd = pwd + "0" + s[i].ToString("x");
                }
                else
                {
                    pwd = pwd + s[i].ToString("x");
                }

            }
            return pwd;
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            lable1.Content = "生成Excel";
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.FileName = TPL_NAME + "_" + GAME_NAME; // Default file name
            dlg.DefaultExt = ".xls"; // Default file extension
            dlg.Filter = "Microsoft Excel |*.xls"; // Filter files by extension
            // Show save file dialog box
            Nullable<bool> result = dlg.ShowDialog();
            // Process save file dialog box results
            if (result == true)
            {
                lable1.Content = "正在生成Excel,请稍候...";
                ExecuteExcel eexcel = new ExecuteExcel();
                eexcel.exportExcel(sw_database, dlg.FileName, TPL_NAME + " " + GAME_NAME, GAME_NAME);
                lable1.Content = "正在生成Excel,请稍候...";
                MessageBox.Show("导出Excel完成!");
            }
            
        }
        public void shaiXuan(string conmmand)
        {
            sw_database = m_datetable;
            if (sw_database == null) return;
            DataRow[] drArr = sw_database.Select(conmmand);//查询
            DataTable dtNew = sw_database.Clone();
            for (int i = 0; i < drArr.Length; i++)
            {
                dtNew.ImportRow(drArr[i]);

            }
            sw_database = dtNew;
            lv.DataContext = sw_database;
        }
        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            ShaiXuan sx = new ShaiXuan(this);
            sx.ShowDialog();
        }

        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            loadTreeView();
        }
        private void loadTreeView()
        {
            lable1.Content = "正在读取服务器配置.....";
            List<TPLList> tpls = new TPLList().GetDBS(getFile("json.txt"));
            List<PropertyNodeItem> itemList = new List<PropertyNodeItem>();
            foreach (TPLList tpl in tpls)
            {

                PropertyNodeItem node1 = new PropertyNodeItem()
                {
                    sw_Icon = AppDomain.CurrentDomain.BaseDirectory + tpl.icon,
                    sw_DisplayName = tpl.mshowname,
                    sw_Name = tpl.mshowname,
                    sw_Parent = null
                };
                foreach (Games game in tpl.games)
                {
                    PropertyNodeItem node1tag1 = new PropertyNodeItem()
                    {
                        sw_Icon = AppDomain.CurrentDomain.BaseDirectory + game.icon,
                        sw_DisplayName = game.showname,
                        sw_Name = game.showname,
                        sw_Parent = node1,
                        gid = game.gid,
                        mid = tpl.mid,
                        sid = game.sid,
                        tag = game.tag
                    };
                    node1.sw_Children.Add(node1tag1);
                }
                //node1.IsExpanded = true;
                itemList.Add(node1);
            }

            this.tvProperties.ItemsSource = itemList;
            lable1.Content = "程序初始化完成!";
        }

        private void tvProperties_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            PropertyNodeItem item = (PropertyNodeItem)tvProperties.SelectedItem;
            if (item.sw_Parent != null)
            {/*
                lable1.Content = "正在获取账号列表...";
                TPL_NAME = item.sw_Parent.sw_Name;
                GAME_NAME = item.sw_Name;
                string getPageStr = getPage(string.Format(GET_ACCOUNT_LIST_URL,item.mid,item.gid ,item.sid, UserMd5(item.mid + item.gid + item.sid + PUBLIC_KEY)));
                lable1.Content = "账号列表获取完毕,正在获取账号数据,请稍后...";
                List<AccountList> accounts = new AccountList().GetDBS(getPageStr);
                loadDate(accounts, item.mid , item.tag , item.sid);
                lable1.Content = "账号数据获取完毕!";*/
                ProgressWPF progresswpf = new ProgressWPF(this, item);
                progresswpf.ShowDialog();
            }
        }
    }

}
